#include "../func.h"

int main(int argc, char* argv[])
{
    if (argc != 3)
    {
        printf("error args\n");
        return -1;
    }

    int sfd;
    sfd = socket(AF_INET, SOCK_STREAM, 0);

    struct sockaddr_in ser;
    memset(&ser, 0, sizeof(ser));
    ser.sin_family = AF_INET;
    ser.sin_port = htons(atoi(argv[2]));
    ser.sin_addr.s_addr = inet_addr(argv[1]);

    int ret;
    ret = connect(sfd, (struct sockaddr*)&ser, sizeof(ser));
	if (-1 == ret)
	{
		perror("connect");
		return -1;
	}

	int epfd = epoll_create(1);
	struct epoll_event event, evs[2];
	memset(&event, 0, sizeof(event));
	event.data.fd = STDIN_FILENO;
	event.events = EPOLLIN;
	ret = epoll_ctl(epfd, EPOLL_CTL_ADD, STDIN_FILENO, &event);
	event.data.fd = sfd;
	event.events = EPOLLIN;
	ret = epoll_ctl(epfd, EPOLL_CTL_ADD, sfd, &event);

	int i;
	int ret1;
	char buf[128];

	while(1)
	{
		memset(evs, 0, sizeof(evs));
		ret1 = epoll_wait(epfd, evs, 2, -1);
		for (i = 0; i < ret1; ++i)
		{
			if (evs[i].data.fd == sfd)
			{
				memset(buf, 0, sizeof(buf));
				ret = recv(sfd, buf, sizeof(buf), 0);
				if (ret > 0)
				{
					printf("%s\n", buf);
				}
				else if (0 == ret)
				{
					printf("byebye\n");
					close(sfd);
					event.data.fd = sfd;
					event.events = EPOLLIN;
					epoll_ctl(epfd, EPOLL_CTL_DEL, sfd, &event);
				}
			}

			if (evs[i].data.fd == 0)
			{
				memset(buf, 0, sizeof(buf));
				ret = read(0, buf, sizeof(buf));
				if (ret > 0)
				{
					ret = send(sfd, buf, strlen(buf) - 1, 0);
					if (ret <= 0)
					{
						printf("send ret = %d\n", ret);
					}
				}
				else
				{
					printf("byebye\n");
					break;
				}
			}
		}
	}

	close(sfd);
    return 0;
}
